package LeetCode;

import java.util.HashMap;
import java.util.LinkedList;

class LRUCache {
    static class Node{
        Integer key;
        Integer value;
        public Node(int key,int value){
            this.key = key;
            this.value  = value;
        }
    }
    private HashMap<Integer,Node> map;
    private LinkedList<Node> list ;
    int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new HashMap<>();
        list = new LinkedList<>();
    }

    public int get(int key) {
        Node n = map.get(key);
        if(n==null) return -1;
        list.remove(n);
        list.addFirst(n);
        return n.value;
    }

    public void put(int key, int value) {
        Node n = map.get(key);
        if(n==null){
            if(capacity==list.size()) {
                Node node = list.removeLast();
                map.remove(node.key);
            }
            Node node = new Node(key, value);
            list.addFirst(node);
            map.put(key,node);
            capacity ++;
        }else{
            n.value = value;
            get(key);
        }
    }
}
